import React, {Component} from 'react'
import {connect} from 'react-redux'
import {NavLeftWrapper} from "./styled";
import {Menu, Icon} from 'antd';
import {actionFunc} from './store'
import {Link} from 'react-router-dom'
import {fromJS} from 'immutable'


class NavLeft extends Component {
    componentWillMount() {
        const node = this.renderNav(this.props.menu)
        this.props.updateMenuTree(node)
    }

    renderNav(data) {
        const SubMenu = Menu.SubMenu;
        return (
            data.map((item) => {
                if (item.get('children')) {
                    return (<SubMenu key={item.get('name')}
                                     title={<span><Icon type="appstore"/><span>{item.get('name')}</span></span>}>
                        {this.renderNav(item.get('children'))}
                    </SubMenu>)
                }
                return (
                    <Menu.Item key={item.get('name')}>
                        <Link to={item.get('link')} >{item.get('name')} </Link>
                    </Menu.Item>
                )
            })

        )
    }

    render() {

        const selectedMenuArr = this.props.selectedMenu.toJS()
        this.handleMenuItemClick = this.props.handleMenuItemCLick.bind(this)
        return (
            <NavLeftWrapper>
                <Menu
                    style={{width: 200}}
                    mode="inline"
                    theme='dark'
                    selectedKeys={selectedMenuArr}
                    onClick = {this.handleMenuItemClick}
                >
                    {this.props.menuTreeNode}
                </Menu>
            </NavLeftWrapper>
        )
    }
}

const mapState = (state) => ({
    menu: state.getIn(['navLeft', 'menu']),
    menuTreeNode: state.getIn(['navLeft', 'menuTreeNode']),
    selectedMenu: state.getIn(['navLeft', 'selectedMenu']),
})
const mapDispatch = (dispatch) => ({
    updateMenuTree(node) {
        dispatch(actionFunc.updateMenuTree(node))
    },
    handleMenuItemCLick(e){
        let menuKey = []
        menuKey.push(e.key)
        dispatch(actionFunc.updateSelectedMenu(fromJS(menuKey)))
    }
})

export default connect(mapState, mapDispatch)(NavLeft)
